//
//  Top10Detail.m
//  LilyBBS
//
//  Created by 李行 on 11-11-5.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "Top10Detail.h"
#import "MessageCell.h"
#import "TFHpple.h"
#import "RegexKitLite.h"
#import "Reply.h"
#import "SingleCookie.h"
#import "LogIn.h"
#import "Reachability.h"

@implementation Top10Detail

@synthesize nameLabel,colorLabel,titlestring,urlString;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView
 {
 }
 */


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    //self.tableView.rowHeight = 300;
    [super viewDidLoad];
    self.navigationItem.title = titlestring;
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
    /*self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] 
     initWithTitle:@"回复"                                            
     style:UIBarButtonItemStyleBordered 
     target:self 
     action:@selector(reply)];*/
    
   
    
   reply = [[UIBarButtonItem alloc] 
                              initWithTitle:@"回复"                                            
                              style:UIBarButtonItemStyleBordered 
                              target:self 
                              action:@selector(reply)];
    
    self.navigationItem.rightBarButtonItem = reply;
    
    Reachability *r = [Reachability reachabilityWithHostName:@"www.nju.edu.cn"];
}

/*- (void)setreplyHidden:(BOOL)hidden{
	NSInteger height = hidden ? 0 : 160;
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:.3];
    //[_replyview.replies setFrame:CGRectMake(20, 0, 280, 100)];
	[_replyview.view setFrame:CGRectMake(10, -5, 300, height)];
    //self.navigationItem.rightBarButtonItem = nil;
    [_replyview.replies becomeFirstResponder];
	[UIView commitAnimations];
}*/

- (void)viewDidUnload
{
    //self.tableView = [[UITableView alloc] initWithFrame:(CGRect) style:<#(UITableViewStyle)#>]
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [[self.items objectAtIndex:0]count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        static NSString *CellIdentifier = @"MessageCellIdentifier";
    
        MessageCell *cell = (MessageCell *)[tableView dequeueReusableCellWithIdentifier: CellIdentifier];
        if (cell == nil) {
            //cell = [[[MessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MessageCell" 
                                                     owner:self options:nil];
            for (id oneObject in nib)
                if ([oneObject isKindOfClass:[MessageCell class]])
                    cell = (MessageCell *)oneObject;
        }
    
        // Configure the cell...
        NSString* i =@"作者:";
        NSString* j = @"\r\n时间:";
        cell.floor.text = [NSString stringWithFormat:@"%i", indexPath.row];
        cell.authortime.text = [[[i stringByAppendingString:[[self.items objectAtIndex:0] objectAtIndex:indexPath.row]] stringByAppendingString:j] stringByAppendingString:[[self.items objectAtIndex:4]objectAtIndex:indexPath.row]];
        cell.title.text = [[self.items objectAtIndex:2] objectAtIndex:indexPath.row];
        cell.ip.text = [[self.items objectAtIndex:5] objectAtIndex:indexPath.row];
        cell.content.text = [[self.items objectAtIndex:3] objectAtIndex:indexPath.row];
        cell.selectionStyle = UITableViewCellEditingStyleNone;
        
        NSString *text = [[self.items objectAtIndex:3] objectAtIndex:indexPath.row];
        CGSize constraint = CGSizeMake(315, 20000);
        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
        
        [cell.content setFrame:CGRectMake(8, 100, 304, MAX(size.height, 20.0f))];
        [cell.ip setFrame:CGRectMake(200,size.height+130, 120, 32)];
        return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row<[[self.items objectAtIndex:0]count]) {
       NSString *text = [[self.items objectAtIndex:3] objectAtIndex:indexPath.row];
    CGSize constraint = CGSizeMake(320 - (10 * 2), 20000.0f);
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    CGFloat height = MAX(size.height, 44.0f);
    return height + 150; 
    }else{
        return 70;
    }
    
}

//item:(author1,authors2,title,text,time,ip)
- (void)getDetail:(NSData*) data{
    TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:data];
    NSMutableArray* arr = [[NSMutableArray alloc] init];
    
    NSMutableArray *floors = [xpathParser searchWithXPathQuery:@"//tr/td[2]"];
    NSMutableArray *authors1 = [xpathParser searchWithXPathQuery:@"//tr/td/a[3]"];
    NSMutableArray* content = [xpathParser searchWithXPathQuery:@"//textarea"];
    NSMutableArray* nextpage = [xpathParser searchWithXPathQuery:@"//center/a[2]/@href"];
    
    
    
    NSMutableArray* authors1arr = [[NSMutableArray alloc] init];
    NSMutableArray* authors2arr = [[NSMutableArray alloc] init];
    NSMutableArray* titlearr = [[NSMutableArray alloc] init];
    NSMutableArray* textarr = [[NSMutableArray alloc] init];
    NSMutableArray* timearr = [[NSMutableArray alloc] init];
    NSMutableArray* iparr = [[NSMutableArray alloc] init];
       
    
	for (TFHppleElement *element in authors1) {
		NSString *strs = [element content];
		[authors1arr addObject:strs];
        //NSLog(@"authors1:%@",strs);
    }    
    
    int number = 0;
	for (TFHppleElement *element in content) {
		NSString *strs = [element content];
        //NSLog(@"strs:%@",strs);
        //NSLog(@"all:%@",strs);
        NSString* text = [[NSString alloc]init];
        if((text = [strs stringByMatching:@"(?<=\\s\\d{4}\\)\\n{2})[\\w\\W]*(?=--)"])==NULL){
            if((text = [strs stringByMatching:@"(?<=\\s\\d{4}\\)\\n{2})[\\w\\W]*"])==NULL){
                if((text=[strs stringByMatching:@"(?<=\\s\\d{4}\\))[\\w\\W]*(?=--)"])==NULL){
                    if((text=[strs stringByMatching:@"(?<=\\s\\d{4}\\))[\\w\\W]*"])==NULL){
                        text = @"无法读取数据";
                    }
                }
            }
        }
        //将空行去除
        /*NSMutableArray* tmpArray = [text componentsSeparatedByString:@"\n"];
         
         int index = 0;
         int number = 0;
         int removeArray [20];
         for(NSString* str in tmpArray){//[str isMatchedByRegex:@"(?<!.)\\r"]||
         if ((![str isMatchedByRegex:@"."])) {
         removeArray[number] = index;
         number++;
         }
         //NSLog(@"%@",str);
         index++;
         }
         
         for (int i=number-1; i>=0; i--) {
         //NSLog(@"%i",removeArray[i]);
         [tmpArray removeObjectAtIndex:removeArray[i]];
         }
         text = [tmpArray componentsJoinedByString:@""];*/
        NSLog(@"text:%@",text);
        [textarr addObject:text];
        
        
        NSArray* authordate = [strs componentsMatchedByRegex:@"(?<=\\().*?(?=\\))"];
        NSString* str1 = [[NSString alloc] init];
        NSString* str2 = [[NSString alloc] init];
        switch ([authordate count]) {
            case 1:
                str1 = @"(无法获取作者)";//author2
                str2 = [authordate objectAtIndex:0];//date
                [authors2arr addObject:str1];
                [timearr addObject:str2];
                break;
            case 3:
                str1 = [authordate objectAtIndex:0];//author2
                str2 = [authordate objectAtIndex:2];//date
                [authors2arr addObject:str1];
                [timearr addObject:str1];
                break;
            case 0:
                str1 = @"(无法获取作者)";//author2
                str2 = @"00:00:00";//date
                [authors2arr addObject:str1];
                [timearr addObject:str2];
                break;
            default:
                str1 = [authordate objectAtIndex:0];//author2
                str2 = [authordate objectAtIndex:1];//date
                [authors2arr addObject:str1];
                [timearr addObject:str2];
                break;
        }
        
        NSString* ip = [strs stringByMatching:@"((2[0-4]\\d|25[0-5]||[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)"];
        if(ip!=NULL){
            [iparr addObject:ip];
        }else{
            ip = @"null";
            [iparr addObject:ip];
        }
        //NSLog(@"ip:%@",ip);
        NSString* title = [strs stringByMatching:@"(?<=\\n).*"];
        [titlearr addObject:title];
        //NSLog(@"title:%@",title);
    }
    
    //存储“下一页”的地址
    /*if ([nextpage count]==0) {
        self.nextPage = @"";
    }else{
        for(TFHppleElement *element in nextpage){
            NSString* strs = [element content];
            self.nextPage = strs;
        }
    }*/
    
    
    [arr addObject:authors1arr];
    [arr addObject:authors2arr];
    [arr addObject:titlearr];
    [arr addObject:textarr];
    [arr addObject:timearr];
    [arr addObject:iparr];
    
    self.items = arr;
    
    /*[authors1 release];
     [content release];
     
     [authors1arr release];
     [authors2arr release];
     [titlearr release];
     [textarr release];
     [timearr release];
     [iparr release];*/
    
    [arr release];
    [xpathParser release];
}

/*-(void)reloadNextPage{
    NSInteger numberOfDetail = [[self.items objectAtIndex:0] count];
    NSString* i = @"http://bbs.nju.edu.cn/";
    NSLog(@"%@",self.nextPage);
    NSString* previoushref = [i stringByAppendingString:self.nextPage];
    NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:previoushref]];
    TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:data];
    NSMutableArray* arr = [[NSMutableArray alloc] init];
    
    NSMutableArray *floors = [xpathParser searchWithXPathQuery:FLOORS];
    NSMutableArray *authors1 = [xpathParser searchWithXPathQuery:AUTHOR];
    NSMutableArray* content = [xpathParser searchWithXPathQuery:@"//textarea"];
    NSMutableArray* nextpage = [xpathParser searchWithXPathQuery:@"//center/a[2]/@href"];
    
    NSLog(@"%d",[floors count]);
    [floors removeObjectAtIndex:0];
    NSLog(@"%d",[floors count]);
    [authors1 removeObjectAtIndex:0];
    [content removeObjectAtIndex:0];
    
    NSMutableArray* authors1arr = [[NSMutableArray alloc] init];
    NSMutableArray* authors2arr = [[NSMutableArray alloc] init];
    NSMutableArray* titlearr = [[NSMutableArray alloc] init];
    NSMutableArray* textarr = [[NSMutableArray alloc] init];
    NSMutableArray* timearr = [[NSMutableArray alloc] init];
    NSMutableArray* iparr = [[NSMutableArray alloc] init]; 
    
    
	for (TFHppleElement *element in authors1) {
		NSString *strs = [element content];
		[[self.items objectAtIndex:0] addObject:strs];
    }    
    
    int number = 0;
	for (TFHppleElement *element in content) {
		NSString *strs = [element content];
        NSString* text = [[NSString alloc]init];
        if((text = [strs stringByMatching:@"(?<=\\s\\d{4}\\)\\n{2})[\\w\\W]*(?=--)"])==NULL){
            if((text = [strs stringByMatching:@"(?<=\\s\\d{4}\\)\\n{2})[\\w\\W]*"])==NULL){
                if((text=[strs stringByMatching:@"(?<=\\s\\d{4}\\))[\\w\\W]*(?=--)"])==NULL){
                    if((text=[strs stringByMatching:@"(?<=\\s\\d{4}\\))[\\w\\W]*"])==NULL){
                        text = @"无法读取数据";
                    }
                }
            }
        }
        NSLog(@"text:%@",text);
        [[self.items objectAtIndex:3] addObject:text];
        
        
        NSArray* authordate = [strs componentsMatchedByRegex:@"(?<=\\().*?(?=\\))"];
        NSString* str1 = [[NSString alloc] init];
        NSString* str2 = [[NSString alloc] init];
        switch ([authordate count]) {
            case 1:
                str1 = @"(无法获取作者)";//author2
                str2 = [authordate objectAtIndex:0];//date
                [[self.items objectAtIndex:1] addObject:str1];
                [[self.items objectAtIndex:4] addObject:str2];
                break;
            case 3:
                str1 = [authordate objectAtIndex:0];//author2
                str2 = [authordate objectAtIndex:2];//date
                [[self.items objectAtIndex:1] addObject:str1];
                [[self.items objectAtIndex:4] addObject:str1];
                break;
            default:
                str1 = [authordate objectAtIndex:0];//author2
                str2 = [authordate objectAtIndex:1];//date
                [[self.items objectAtIndex:1] addObject:str1];
                [[self.items objectAtIndex:4] addObject:str2];
                break;
        }
        
        NSString* ip = [strs stringByMatching:@"((2[0-4]\\d|25[0-5]||[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)"];
        if(ip!=NULL){
            [[self.items objectAtIndex:5] addObject:ip];
        }else{
            ip = @"null";
            [[self.items objectAtIndex:5] addObject:ip];
        }
        //NSLog(@"ip:%@",ip);
        NSString* title = [strs stringByMatching:@"(?<=\\n).*"];
        [[self.items objectAtIndex:2] addObject:title];
        //NSLog(@"title:%@",title);
    }
    //存储“下一页”的地址
    if ([nextpage count]==0) {
        self.nextPage = @"";
    }else{
        for(TFHppleElement *element in nextpage){
            NSString* strs = [element content];
            self.nextPage = strs;
        }
    }
    
    [arr release];
    [xpathParser release];
    
    [self.tableView reloadData];
}*/

-(void)reply{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.nju.edu.cn"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            //没有网络连接
            NSLog(@" ");
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"回复提示" message:@"尚未登录，请登录后回复。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
            [alert show];
            [alert release];
            return;
        case ReachableViaWWAN:
            //使用3G网络            
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络            
            break;
    }
    
    //若未登录，则提示
    if ([[SingleCookie sharedSingleCookie].savedCookies count]==0) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"回复提示" message:@"尚未登录，请登录后回复。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
        [alert show];
        [alert release];
        return;
        //[self dismissModalViewControllerAnimated:YES];
    }
    //Reply* reply = [[Reply alloc] initWithNibName:@"Reply" bundle:nil];
   
    //UINavigationController *replyCon = [[UINavigationController alloc] initWithRootViewController:reply];
    //[self presentModalViewController:replyCon animated:YES];
    _replyview = [[Reply alloc] init];
    [_replyview.view setFrame:CGRectMake(10, -5, 300, 0)];
    [self.view addSubview:_replyview.view];
    [UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:.3];
    [_replyview.view setFrame:CGRectMake(10, -5, 300, 160)];
    [_replyview.replies becomeFirstResponder];
    _replyview.reptitle.text =[NSString stringWithFormat:@"RE:%@",titlestring];
    _replyview.urlString = self.urlString;
    [_replyview.cancelbtn addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
     self.navigationItem.rightBarButtonItem = nil;
    NSLog(@"urlString:%@",_replyview.urlString);
	[UIView commitAnimations];
   
}

- (void) dealloc{
    [nameLabel release];
    [colorLabel release];
    [urlString release];
    [super dealloc];
}
     
-(void)cancel:(id)sender{
         [_replyview.replies resignFirstResponder];
         [UIView beginAnimations:nil context:nil];
         [UIView setAnimationDuration:.2];
         [_replyview.view setFrame:CGRectMake(10, -5, 300, 0)];
         
         [UIView commitAnimations];
    self.navigationItem.rightBarButtonItem = reply;
    
    [_replyview dealloc];
    
         //[self becomeFirstResponder];
         //[self dismissModalViewControllerAnimated:YES];
}

#pragma UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            break;
        case 1:
            NSLog(@"logging in...");
            LogIn* login = [[LogIn alloc] initWithNibName:@"LogIn" bundle:nil];
            UINavigationController *addNavCon = [[UINavigationController alloc] initWithRootViewController:login];
            [self presentModalViewController:addNavCon animated:YES];
            [login release];
            break;
            
        default:
            break;
    }
}

@end
